package com.jy.api.controller.web;

import com.jy.api.dao.MemberAccountDao;
import com.jy.api.dao.MemberDao;
import com.jy.api.dao.OrderDao;
import com.jy.api.domain.Member;
import com.jy.api.domain.MemberAccount;
import com.jy.api.domain.Order;
import com.jy.api.domain.SMSType;
import com.jy.api.exception.MyException;
import com.jy.api.service.MemberAccountService;
import com.jy.api.service.MemberService;
import com.jy.api.service.OrderService;
import com.jy.api.service.VerificationCodeService;
import com.jy.api.util.Contens;
import com.jy.api.util.ISyncExecutor;
import com.jy.api.util.RedisSyncLocker;
import com.jy.api.util.ValidatorUtil;
import com.jy.api.vo.web.MemberVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

/**
 * Created by lihu on 2017/12/6.
 */
@Slf4j
@RestController
@RequestMapping(value = "v1/web", produces = "application/json;charset=utf-8")
public class WebMemberController {


    @Autowired
    OrderDao orderDao;


    @Autowired
    MemberService memberService;

    @Autowired
    MemberDao memberDao;

    @Autowired
    private OrderService orderService;
    @Autowired
    private RedisSyncLocker redisSyncLocker;
    @Autowired
    VerificationCodeService verificationCodeService;
    @Autowired
    private MemberAccountDao memberAccountDao;
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    /**
     * 获取会员信息
     *
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "/stores/{storeId}/member-info")
    public ResponseEntity queryMember(@PathVariable String storeId,
                                      @RequestParam(name = "memberId") String memberId) {
        try {
            MemberVo memberVo = memberService.getMemberInfo(storeId, memberId);
            return new ResponseEntity(memberVo, HttpStatus.OK);
        } catch (MyException ex) {
            log.error("getMemberInfo is error==> storeId:{},memberId:{}", storeId, memberId, ex);
            return new ResponseEntity(ex.getMessage(), HttpStatus.BAD_REQUEST);
        } catch (Exception ex) {
            log.error("getMemberInfo is error==> storeId:{},memberId:{}", storeId, memberId, ex);
            return new ResponseEntity("系统运行错误", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }





    /**
     * 短信发送
     *
     * @param mobile 手机号
     * @return message
     */
    @RequestMapping(value = "/member/mobile/code", method = RequestMethod.GET)
    public ResponseEntity memberMobileCode(@RequestParam("mobile") String mobile,@RequestParam("storeId") String storeId) {

        try {
            if (!ValidatorUtil.isMobile(mobile)) {
                return ResponseEntity.badRequest().body("电话号码有误");
            }
            Member member = memberDao.findTop1ByMobileOrderByUpdateTimeDesc(mobile);
            if (member==null){
                return ResponseEntity.badRequest().body("您还不是本店铺会员，加会员请联系工作人员");
            }
            MemberAccount memberAccount = memberAccountDao.getStoreIdAndMemberId(storeId,member.getId());
            if (memberAccount==null){
                return ResponseEntity.badRequest().body("您还不是本店铺会员，加会员请联系工作人员");
            }
            String msg = verificationCodeService.setCode(mobile, SMSType.ACCOUNT);
            if (StringUtils.isBlank(msg)) {
                return ResponseEntity.ok().build();
            } else {
                return ResponseEntity.badRequest().body(msg);
            }
        } catch (Exception ex) {
            log.error("verificationCode is error:{}", ex);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ex.getMessage());
        }

    }


    /**
     * 验证短信验证码
     *
     * @param mobile 手机号
     * @return message
     */
    @RequestMapping(value = "/member/mobile", method = RequestMethod.GET)
    public ResponseEntity verificationCode(@RequestParam("mobile") String mobile,@RequestParam("storeId") String storeId,@RequestParam("orderId") String orderId,@RequestParam("code") String code) {

        try {

            String key = Contens.SMS_KEY.replace("MOBILE", mobile).
                    replace("TYPE", SMSType.ACCOUNT.toString());
            if (!StringUtils.equals(stringRedisTemplate.opsForValue().get(key), code)) {
                return new ResponseEntity("验证码输入有误，请重新输入", HttpStatus.BAD_REQUEST);
            }
            if (!ValidatorUtil.isMobile(mobile)) {
                return ResponseEntity.badRequest().body("电话号码有误");
            }
            Member member = memberDao.findTop1ByMobileOrderByUpdateTimeDesc(mobile);
            if (member==null){
                return ResponseEntity.badRequest().body("您还不是本店铺会员，加会员请联系工作人员");
            }
            MemberAccount memberAccount = memberAccountDao.getStoreIdAndMemberId(storeId,member.getId());
            if (memberAccount==null){
                return ResponseEntity.badRequest().body("您还不是本店铺会员，加会员请联系工作人员");
            }
            Order order = orderDao.findOne(orderId);
            if (order == null) {
                return new ResponseEntity("查询失败！订单信息不存在！", HttpStatus.BAD_REQUEST);
            }
            order.setMemberId(member.getId());
            order.setMemberName(member.getName());
            MemberVo memberVo = null;
            //订单绑定会员信息
            if (StringUtils.isNotBlank(order.getMemberId())) {
                memberVo = memberService.getMemberInfo(order.getStoreId(), order.getMemberId());
                memberVo.setOrder(orderService.judgeWebOrderItem(order));
            }
            return new ResponseEntity(memberVo, HttpStatus.OK);
        } catch (Exception ex) {
            log.error("verificationCode is error:{}", ex);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ex.getMessage());
        }

    }

















    /**
     * 获取会员信息
     *
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "/{orderId}/member-info")
    public ResponseEntity getMemberInfo(@PathVariable String orderId) {
        try {
            return (ResponseEntity) redisSyncLocker.idLock(orderId, o -> {
                Order order = orderDao.findOne(orderId);
                if (order == null) {
                    return new ResponseEntity("查询失败！订单信息不存在！", HttpStatus.BAD_REQUEST);
                }
                MemberVo memberVo = null;
                //订单绑定会员信息
                if (StringUtils.isNotBlank(order.getMemberId())) {
                    memberVo = memberService.getMemberInfo(order.getStoreId(), order.getMemberId());
                    memberVo.setOrder(orderService.judgeWebOrderItem(order));
                }

                return new ResponseEntity(memberVo, HttpStatus.OK);
            });
        } catch (MyException ex) {
            log.error("getMemberInfo is error==> orderId:{}", orderId, ex);
            return new ResponseEntity(ex.getMessage(), HttpStatus.BAD_REQUEST);
        } catch (Exception ex) {
            log.error("getMemberInfo is error==> orderId:{}", orderId, ex);
            return new ResponseEntity("系统运行错误", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 获取会员信息
     *
     * @param orderId
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "/member")
    public ResponseEntity getMember(@RequestParam(name = "orderId") String orderId,
                                    @RequestParam(name = "openId") String openId) {
        try {
            Order order = orderDao.findOne(orderId);
            if (order == null) {
                return new ResponseEntity("查询失败！订单信息不存在！", HttpStatus.BAD_REQUEST);
            }
            Member member = memberDao.findOne(order.getMemberId());
            if (member == null || !StringUtils.equals(member.getOpenId(), openId)) {
                return new ResponseEntity("请使用安全登陆微信号进行扫码支付！", HttpStatus.BAD_REQUEST);
            }
            MemberVo memberVo = null;
            //订单绑定会员信息
            if (StringUtils.isNotBlank(order.getMemberId())) {
                memberVo = memberService.getMemberInfo(order.getStoreId(), member);
            }
            return new ResponseEntity(memberVo, HttpStatus.OK);
        } catch (MyException ex) {
            log.error("getMemberInfo is error==> orderId:{}", orderId, ex);
            return new ResponseEntity(ex.getMessage(), HttpStatus.BAD_REQUEST);
        } catch (Exception ex) {
            log.error("getMemberInfo is error==> orderId:{}", orderId, ex);
            return new ResponseEntity("系统运行错误", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}
